package com.lzx.iteam;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.*;
import android.view.animation.AnimationUtils;
import android.widget.*;
import cn.jpush.android.api.JPushInterface;
import com.lzx.iteam.bean.AppMessage;
import com.lzx.iteam.net.*;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.TextMoreView;
import com.umeng.analytics.MobclickAgent;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

/**
 * Created by zhangshuai on 15-3-16.
 */
public class SettingActivity extends Activity implements View.OnClickListener {


    private TextMoreView mResetPw;
    private TextMoreView mCheck;
    private TextMoreView mAsk;
    private TextMoreView mCustom;
    private TextMoreView mManager;
    private TextMoreView mUser;
    private LinearLayout mBack;
    private TextView mOut;
    private TextView mTvVersion;

    private TextMoreView mHelp;
    private TextMoreView mQuestion;
    private TextMoreView mQrCode;
    private TextMoreView mUpgrade;

    private PreferenceUtil mPreferenceUtil;
    private ArrayList<String> nameCard;
    private String mMyName;
    private String mMyAvatar;
    private AllDialogUtil dialogUtil;
    private AsynHttpClient mAsynClient;
    private CloudDBOperation mCloudDBOperation;
    private PopupWindow mQrCodeWindow;
    private ImageView mIvDimension;
    private Bitmap bmp = null;

    private final int MSG_DEACTIVE = 2002;
    private final int MSG_GET_VERSION = 1792;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case MSG_DEACTIVE:
                    if (msg.arg1 == 0) {
/*
                        NetServiceManager.unbindNetChatService(SettingActivity.this.getApplicationContext());
*/
                        LocalLogin.getInstance().localDeactive(SettingActivity.this);
                        JPushInterface.stopPush(getApplicationContext());
                        Toast.makeText(SettingActivity.this, "退出成功",
                              Toast.LENGTH_LONG).show();
//                        clearAppUserData("com.lzx.iteam");
                        Intent intent = new Intent(SettingActivity.this, LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                        MainActivity.mActivity.finish();
                        SettingActivity.this.finish();
                    } else {

                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(SettingActivity.this, R.string.active_failure_no_network,
                                  Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(SettingActivity.this, (String) msg.obj,
                                  Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case MSG_GET_VERSION:
                    if (msg.arg1 == 0) {
                        AppMessage appMessage = (AppMessage) msg.obj;
                        if (StringUtil.isEmpty(appMessage.getVersion())) {
                            Toast.makeText(SettingActivity.this, "已经是最新版本", Toast.LENGTH_LONG).show();
                        } else {
                           /* if (("ch_baidu").equals(ChannelUtil.getChannel(SettingActivity.this)) || ("ch_sj91").equals(ChannelUtil.getChannel(SettingActivity.this))) {
                                BDAutoUpdateSDK.uiUpdateAction(SettingActivity.this, new UICheckUpdateCallback() {
                                    @Override
                                    public void onCheckComplete() {

                                    }
                                });
                            } else {*/
                            checkVersion(appMessage.getVersion(), appMessage.getVersionLog(), appMessage.getDownload());
                          /*  }*/
                        }

                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting_layout);
        mPreferenceUtil = PreferenceUtil.getInstance(this);
        mCloudDBOperation = new CloudDBOperation(this);
        initView();
        initProperty();
        mTvVersion.setText("V " + Constants.getVersionName(this));

        String channel = ChannelUtil.getChannel(SettingActivity.this).trim();
//        Toast.makeText(SettingActivity.this, "channel == " + channel, Toast.LENGTH_SHORT).show();
        Log.d("My_channel","channel == " + channel);
    }

    public void initView() {
        mBack = (LinearLayout) findViewById(R.id.setting_ll_back);
        mBack.setOnClickListener(this);
        mResetPw = (TextMoreView) findViewById(R.id.setting_tm_pw);
        mResetPw.setOnClickListener(this);
        mResetPw.setImageGone();
        mCheck = (TextMoreView) findViewById(R.id.setting_tm_check);
        mCheck.setOnClickListener(this);
        mCheck.setImageGone();
        mOut = (TextView) findViewById(R.id.setting_out);
        mOut.setOnClickListener(this);
        mAsk = (TextMoreView) findViewById(R.id.setting_tm_ask);
        mAsk.setOnClickListener(this);
        mAsk.setImageGone();
        /*mCustom = (TextMoreView) findViewById(R.id.setting_tm_custom);
        mCustom.setOnClickListener(this);
        mCustom.setImageGone();*/
        mManager = (TextMoreView) findViewById(R.id.setting_tm_manager);
        mManager.setOnClickListener(this);
        mManager.setImageGone();
        mUser = (TextMoreView) findViewById(R.id.setting_tm_user);
        mUser.setOnClickListener(this);
        mUser.setImageGone();
        mHelp = (TextMoreView) this.findViewById(R.id.function_tm_help);
        mHelp.setOnClickListener(this);
        mHelp.setImageGone();
        mQuestion = (TextMoreView) this.findViewById(R.id.function_tm_question);
        mQuestion.setOnClickListener(this);
        mQuestion.setImageGone();
        mQrCode = (TextMoreView) this.findViewById(R.id.tm_qrcode);
        mQrCode.setOnClickListener(this);
        mQrCode.setImageGone();
        mUpgrade = (TextMoreView) this.findViewById(R.id.function_tm_upgrade);
        mUpgrade.setOnClickListener(this);
        mUpgrade.setImageGone();
        mTvVersion = (TextView) findViewById(R.id.setting_tv_version);


    }

    public void initProperty() {
        dialogUtil = AllDialogUtil.getInstance(this);
        mAsynClient = AsynHttpClient.getInstance(this);
    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.setting_ll_back:
                finish();
                break;
            case R.id.setting_tm_pw:
                Intent intent = new Intent(this, ResetPswActivity.class);
                startActivity(intent);
                break;
            case R.id.setting_tm_check:
                getVersionMessage();
                break;
            /*case R.id.setting_tm_custom:
                Intent custom = new Intent(this,CompanyCustomActivity.class);
                startActivity(custom);
                break;*/
            case R.id.setting_out:
                // 暂时
                showAlarmDialog();
                break;
            case R.id.setting_tm_ask:// 联系我们
                Intent ask = new Intent(this, WebViewActivity.class);
                ask.putExtra("title", "联系我们");
                ask.putExtra("type", -1);
                startActivity(ask);
                break;
            case R.id.function_tm_help: // 操作帮助
                intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("title", "操作帮助");
                intent.putExtra("type", 0);
                startActivity(intent);
                break;
            case R.id.function_tm_question:  // 问题反馈
                intent = new Intent(this, FeedActivity.class);
                startActivity(intent);
                break;
            case R.id.tm_qrcode: // 二维码名片
                nameCard = (ArrayList<String>) mPreferenceUtil.getCloudContact(Constants.CONTACT_NAME_CARD);
                if (nameCard == null) {
                    Toast.makeText(this, "名片信息为空，请先设置名片", Toast.LENGTH_SHORT).show();
                } else {
                    mMyName = nameCard.get(0);
                    mMyAvatar = nameCard.get(7);
                    showQrCodePop();
                }
                break;
            case R.id.function_tm_upgrade:
                //目前已废弃此功能
                Intent upgrade = new Intent(SettingActivity.this, AccountUpgradeActivity.class);
                startActivity(upgrade);
                break;
            case R.id.setting_tm_manager:
                Intent web = new Intent();
                web.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse("http://7xk9ph.com1.z0.glb.clouddn.com/pdf/the-administrator-installation-manual.pdf");
                web.setData(content_url);
                startActivity(web);
               /* intent = new Intent(this, PDFViewActivity.class);
                intent.putExtra("title","管理员安装手册");
                intent.putExtra("type",0);
                startActivity(intent);*/
                break;
            case R.id.setting_tm_user:
                web = new Intent();
                web.setAction("android.intent.action.VIEW");
                content_url = Uri.parse("http://7xk9ph.com1.z0.glb.clouddn.com/pdf/iTeam-training-manual-for-employees.pdf");
                web.setData(content_url);
                startActivity(web);
                /*intent = new Intent(this, PDFViewActivity.class);
                intent.putExtra("title","i团队培训手册（员工版）");
                intent.putExtra("type",1);
                startActivity(intent);*/
                break;
        }
    }

    /**
     * 弹出二维码
     */
    private void showQrCodePop() {
        View mainView = LayoutInflater.from(this).inflate(R.layout.function_qrcode_pop_layout, null);
        ImageView head = (ImageView) mainView.findViewById(R.id.function_pop_head);
        ImageLoaderInterface.imageLoader.displayImage(mMyAvatar, head, ImageLoaderInterface.optionHeadImage);

        mIvDimension = (ImageView) mainView.findViewById(R.id.dimension_code);
        setQrCode(nameCard);
        TextView mName = (TextView) mainView.findViewById(R.id.function_pop_name);
        mName.setText(mMyName);
        LinearLayout qrcode = (LinearLayout) mainView.findViewById(R.id.function_pop_qrcode);

        mQrCodeWindow = new PopupWindow(this);
        mQrCodeWindow.setBackgroundDrawable(new BitmapDrawable());
        mQrCodeWindow.setFocusable(true);
        mQrCodeWindow.setTouchable(true);
        mQrCodeWindow.setOutsideTouchable(true);
        mQrCodeWindow.setContentView(mainView);
        mQrCodeWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mQrCodeWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        mQrCodeWindow.showAtLocation(mainView, Gravity.CENTER, 0, 0);
        mQrCodeWindow.update();
        mainView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.alpha_in));
        qrcode.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        mainView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mQrCodeWindow.dismiss();
                return false;
            }
        });

    }

    /**
     * 设置我的二维码
     *
     * @param nameCard
     */
    public void setQrCode(ArrayList<String> nameCard) {
        String qrcodeString = QrCodeUtil.enQrCodeOneContact(nameCard);
        bmp = QrCodeUtil.createQrcode(qrcodeString, this);
        mIvDimension.setImageBitmap(bmp);
        mIvDimension.setBackgroundResource(R.color.transbg);
    }

    /**
     * 退出提示
     */
    public void showAlarmDialog() {
        String stopAlarm = "提示";
        String message = "是否退出当前账号";
        dialogUtil.titleMsgBtnClick(stopAlarm, message, "确定", "取消");
        dialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {

                mobileDeactive();
                lDialog.dismiss();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
            }
        });

    }

    /**
     * 退出发送请求
     */
    public void mobileDeactive() {


        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));

        MobileDeactiveMessage mobileDeactiveMsg = new MobileDeactiveMessage(
              mHandler.obtainMessage(MSG_DEACTIVE));
        mobileDeactiveMsg.mParams = nvps;
        mobileDeactiveMsg.mApi = AsynHttpClient.API_USER_LOGOUT;
        mAsynClient.execUserHttp(mobileDeactiveMsg);
    }


    class MobileDeactiveMessage extends CcMsgStructure {

        private Message mmCallback;

        public MobileDeactiveMessage(Message callback) {
            mmCallback = callback;
        }

        @Override
        public void onReceive(JSONObject data) {
            if (mmCallback != null)
                mmCallback.arg1 = 0;
            mmCallback.sendToTarget();
        }

        @Override
        public void onError(int error, Object ret) {

            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if (mmCallback != null) {
                mmCallback.arg1 = error;
                if (!StringUtil.isEmpty(errorMsg)) {
                    mmCallback.obj = errorMsg;
                } else {
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }

    /**
     * 版本更新
     */
    public void checkVersion(String versionCode, String versionLog, final String downloadUrl) {
        //MobclickAgent.updateOnlineConfig(this);
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (mWifi.isConnected()) {
            try {
                if (!versionCode.equals(Constants.getVersionName(SettingActivity.this))) {
                    //show dialog
                    dialogUtil.titleMsgBtnStyle("发现新版本：" + versionCode, versionLog, "现在下载", "以后再说");
                    dialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
                        @Override
                        public void onConfirmClick(Dialog lDialog) {
                            lDialog.dismiss();
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri content_Uri = Uri.parse(downloadUrl);
                            intent.setData(content_Uri);
                            startActivity(intent);
                        }

                        @Override
                        public void onCancelClick(Dialog lDialog) {
                            lDialog.dismiss();
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 进入app
     * 1. 关闭推送接口
     * 2. 检查socket是否连接
     * 3. app版本检查
     */
    private void getVersionMessage() {
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_CLIENT_TYPE, "1"));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_APP_VERSION, Constants.getVersionName(this)));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_VERSION, Constants.getVersionName(this)));
        GetAppMessageMsg message = new GetAppMessageMsg(mHandler.obtainMessage(MSG_GET_VERSION));
        message.mApi = AsynHttpClient.API_APP_VERSION;
        message.mParams = mList;
        AsynHttpClient.getInstance(this).execUserHttp(message);

    }

}
